<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\common\model;

use think\Model;

/**
 * 商品标签模型
 */
class GoodsTag extends Model
{
    // 设置表名
    protected $name = 'goods_tag';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    /**
     * 标签与商品的多对多关联
     */
    public function goods()
    {
        return $this->belongsToMany(Goods::class, GoodsTagRelation::class, 'goods_id', 'tag_id');
    }

    // 搜索器
    public function searchKeywordAttr($query, $value, $data)
    {
        if ($value) {
            $query->where('name', 'like', '%' . $value . '%');
        }
    }

    // 状态搜索器
    public function searchStatusAttr($query, $value, $data)
    {
        if ($value !== '') {
            $query->where('status', $value);
        }
    }

    /**
     * 获取热门标签列表
     * @param int $limit 限制数量
     * @return array 标签列表
     */
    public static function getHotTags($limit = 10)
    {
        return self::withCount(['goods' => function ($query) {
            $query->where('status', 1);
        }
        ])
            ->order('goods_count', 'desc')
            ->limit($limit)
            ->select()
            ->toArray();
    }
}